<template>
  <div class="categories">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="categories-card">
      <!-- 添加按钮 -->
      <el-button type="primary" @click="addCategories">添加分类</el-button>

      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- 模板 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-circle-check"
            style="color:#20b2aa"
            v-if="scope.row.cat_deleted===false "
          ></i>
          <i class="el-icon-circle-close" style="color:red" v-else></i>
        </template>
        <!-- 自定义order模板 -->
        <template slot="order" slot-scope="scoped">
          <el-tag size="mini" v-if="scoped.row.cat_level===0">一级</el-tag>
          <el-tag type="success" size="mini" v-if="scoped.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" size="mini" v-if="scoped.row.cat_level===2">三级</el-tag>
        </template>
        <!-- 自定义操作模板 -->
        <template slot="opt" slot-scope="scoped">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCateId(scoped.row.cat_id)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete-solid"
            size="mini"
            @click="deleteCate(scoped.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>

      <!-- 分页的组件 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加的弹框 -->
      <el-dialog title="添加分类" :visible.sync="addCategoriesDialog" width="40%">
        <!-- 添加分类的表单 -->
        <el-form
          label-width="100px"
          class="demo-ruleForm"
          :model="addcatemodel"
          :rules="addRules"
          ref="addRef"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addcatemodel.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectedList"
              :options="parentCateList"
              :props="cascaderProp"
              @change="cascaderChange"
              style="width:100%"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategoriesDialog = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <!--编辑的弹框  -->
      <el-dialog title="编辑分类" :visible.sync="editCategoriesDialog" width="40%">
        <el-form :model="editcatemodel"  ref="editRef">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editcatemodel.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCategoriesDialog = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { log } from "util";
export default {
  data() {
    return {
      // 商品分类的数组
      cateList: [],
      queryInfo: {
        type: "3",
        pagenum: 1,
        pagesize: 5
      },
      //   一共多少条数据
      total: 0,
      //   表格中的数据
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          prop: "cat_deleted",
          type: "template",
          template: "isok"
        },
        {
          label: "排序",
          prop: "cat_level",
          type: "template",
          template: "order"
        },
        { label: "操作", template: "opt", type: "template" }
      ],
      //添加的对话框
      addCategoriesDialog: false,
      addcatemodel: {
        cat_name: "",
        cat_level: 0,
        cat_pid: 0
      },
      //   添加分类的校验
      addRules: {},
      // 父级分类列表
      parentCateList: [],
      //级联选择框框的配置对象
      cascaderProp: {
        value: "cat_pid",
        label: "cat_name",
        children: "children"
      },
      // 父类被选中的id存在数组中
      selectedList: [],
      // 编辑的弹框
      editCategoriesDialog: false,
      editcatemodel: {
        cat_name: ""
      }
    };
  },
  methods: {
    //  渲染商品分类的数据
    async getCategories() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });

      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    // 页码
    handleCurrentChange(num) {
      this.queryInfo.pagenum = num;
      this.getCategories();
    },
    // 添加分类
    async addCategories() {
      this.addCategoriesDialog = true;
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200) {
        return this.$message.error("");
      }
      this.parentCateList = res.data;
    },
    // 当选中项的时候获取那个名字
    cascaderChange() {
      //如果没有选中 那么就是一级
      if (this.selectedList.length == 0) {
        this.addcatemodel.cat_pid = 0;
        this.addcatemodel.cat_level = 0;
      } else {
        this.addcatemodel.cat_pid = this.selectedList[
          this.selectedList.length - 1
        ];
        this.addcatemodel.cat_level = this.selectedList.length;
      }
    },
    // 点击确定的时候 把数据传给服务器
    addCate() {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return false;

        const { data: res } = await this.$http.post(
          "categories",
          this.addcatemodel
        );
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败");
        }
        this.addCategoriesDialog = false;
        this.getCategories();
      });
    },
    // 删除分类
    async deleteCate(id) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        return "clac";
      });
      // console.log(result)
      if (result == "clac") {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      } else if (result == "confirm") {
        const { data: res } = await this.$http.delete(`categories/${id}`);
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.$message.success("删除成功");
        this.getCategories();
      }
    },
    // 根据id回显数据
    async editCateId(id) {
      this.editCategoriesDialog = !this.editCategoriesDialog;
      const { data: res } = await this.$http.get(`categories/${id}`);
      console.log(res);
      this.editcatemodel = res.data;
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类名称失败");
      }
    },
    //确定更改
    editCate() {
      this.$refs["editRef"].validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.editcatemodel.cat_id}`,
          this.editcatemodel
        );
        console.log(res);
        if(res.meta.status!==200){
          return this.$message.error("更新失败")
        }
        this.$message.success("更新成功");
        this.editCategoriesDialog=false;
        this.getCategories()
      });
    }
  },
  created() {
    this.getCategories();
  }
};
</script>

<style lang="less" scoped>
.categories-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 10px;
}
</style>

